public class RomanNumberConverter {

  private final static String[] BASIC_ROMAN_NUMBERS = { "M", "CM", "D", "CD","C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
  private final static int[] BASIC_VALUES = { 1000, 900, 500, 400, 100, 90,50, 40, 10, 9, 5, 4, 1 };

  public static int convert(String romanNumber) throws UnsupportedOperationException {
    if ( !valideRomanNumber(romanNumber) ){
      throw new IllegalArgumentException("Nombre romain invalide \n");
    } 

    int nombreConverti = 0;
    int courante = 0;
    int precedente = 0;

    for(int i=romanNumber.length()-1 ; i>=0 ; i -= 2) {
      courante = value(romanNumber.charAt(i));
      if( i > 0 )
        precedente = value(romanNumber.charAt(i-1));
      else
        precedente = 0;
      nombreConverti += courante + ( precedente < courante ? -precedente : precedente );
    }

    return nombreConverti;
  }

  private static int value(char c){
    if( c == 'I'){
      return 1;
    }
    if( c == 'V'){
      return 5;
    }
    if( c == 'X'){
      return 10;
    }
    if( c ==  'L'){
      return 50;
    }
    if( c == 'C'){
      return 100;
    }
    if( c == 'D'){
      return 500;
    }
    if( c == 'M'){
      return 1000;
    }

    return -1;
  }

  public static String convert(int number) throws UnsupportedOperationException {
    String convertedNumber = new String();

    if( number <= 0 )
      throw new IllegalArgumentException("Le chiffre doit être supérieur à 0");
    int remainder = number;
    for (int i = 0; i < BASIC_VALUES.length; i++) {
      while (remainder >= BASIC_VALUES[i]) {
        convertedNumber += BASIC_ROMAN_NUMBERS[i];
        remainder -= BASIC_VALUES[i];
      }
    }
    return convertedNumber;
  }

  private static boolean valideRomanNumber(String s){
    int nbI = 0;
    int nbV = 0;
    int nbX = 0;
    int nbL = 0;
    int nbC = 0;
    int nbD = 0;

    for(int i=0; i<s.length() ; i++){
      if(nbI == 4 || nbV == 4 || nbX == 4 || nbL == 4 || nbC == 4 || nbD == 4){
        return false;
      }
      if(s.charAt(i) =='I')
        nbI++;
      else if(s.charAt(i) =='V')
        nbV++;
      else if(s.charAt(i) =='X')
        nbX++;
      else if(s.charAt(i) =='L')
        nbL++;
      else if(s.charAt(i) =='C')
        nbC++;
      else if(s.charAt(i) =='D')
        nbD++;
      else if(s.charAt(i) != 'M')
        return false;
    }
    return true;
  }
}
